import os
import requests
import json
import re
from client.func.Encryption import md5
from client.func.ImgOperate import read_img, copy_img, get_str_base64, change_alink

server_host = "http://127.0.0.1:5000/"
temp_key = {}

img_dir = "client/.cache/img_buf/"  # 头像存储位置
history_dir = "client/history/"  # 聊天记录存储位置


def get_update_post(uid, host=server_host):
    """获取主界面是否刷新标志"""
    global temp_key
    try:
        kw = {
            "uid": uid,
            "key": temp_key[uid]
        }
        reply = requests.get(host + 'get_update/', json=kw).json()
        return True, reply["Remote_landing"], reply["status"], reply["sound"]
    except Exception as e:
        print("get_update_post:", e)
        return False, False, False, False


def login_post(uid, password, host=server_host):
    """登陆请求"""
    global temp_key
    dic = {
        "uid": uid,
        "password": md5(password)
    }
    try:
        reply = requests.post(host+'login/', json=dic).json()
        temp_key[uid] = reply["key"]
        return reply["status"], reply["info"]
    except:
        return False, u"服务器连接失败!"


def register_post(uid, password, name, host=server_host):
    """注册请求"""
    dic = {
        "uid": uid,
        "password": md5(password),
        "name": name
    }
    try:
        reply = requests.post(host + 'register/', json=dic).json()
        return reply["status"], reply["info"]
    except:
        return False, u"服务器连接失败!"


def get_user_main_post(uid, host=server_host):
    """获取主界面参数请求"""
    global temp_key
    global img_dir
    try:
        kw = {
            "uid": uid,
            "key": temp_key[uid]
        }
        reply = requests.get(host + 'user_main/', json=kw).json()
        for user in reply["Friend"]:
            img = get_img_post(user["img"])
            if img:
                copy_img(img_dir + user["img"], img)
        for group in reply["Group"]:
            img = get_img_post(group["img"])
            if img:
                copy_img(img_dir + group["img"], img)
        return reply["status"], reply["Friend"], reply["Group"], reply["NewFriend"]
    except Exception as e:
        print("get_user_main_post:", e)
        return False, [], [], 0


def change_new_friend_num_post(uid, new_friend_num=0, host=server_host):
    """修改新朋友消息显示参数请求"""
    global temp_key
    try:
        kw = {
            "uid": uid,
            "key": temp_key[uid],
            "NewFriend": new_friend_num
        }
        reply = requests.post(host + 'change_new_friend_num/', json=kw).json()
        return reply["status"]
    except:
        return False


def get_img_post(img_path, host=server_host):
    """获取头像请求"""
    try:
        kw = {
            "img_path": img_path
        }
        reply = requests.post(host + 'get_img/', json=kw).json()
        return reply["img"]
    except Exception as e:
        print(e)
        return None


def save_img_post(uid, img_path, mode, host=server_host):
    """上传头像请求"""
    img_base64 = read_img(img_path)
    try:
        kw = {
            "uid": uid,
            "img": img_base64,
            "mode": mode
        }
        reply = requests.post(host + 'save_img/', json=kw).json()
        return reply["status"]
    except Exception as e:
        print(e)
        return False


def get_user_info_post(uid, host=server_host):
    """获取用户信息请求"""
    global img_dir
    try:
        kw = {
            "uid": uid
        }
        reply = requests.get(host + 'get_user_info/', json=kw).json()
        if reply["status"]:
            img = get_img_post(reply["img"])
            if img:
                copy_img(img_dir+reply["img"], img)
            return reply["status"], reply["name"], reply["img"], reply["sex"], reply["search_accept"], reply["explain"]
        else:
            return None
    except:
        return None


def change_user_info_post(uid, info, host=server_host):
    """修改用户信息请求"""
    global temp_key
    try:
        kw = {
            "uid": uid,
            "key": temp_key[uid],
            "info": info
        }
        save_img_post(uid, info["img_path"], "friend")
        reply = requests.post(host + 'change_user_info/', json=kw).json()
        return reply["status"]
    except:
        return False


def change_password_post(uid, pswd, new_pswd, host=server_host):
    """修改密码请求"""
    global temp_key
    try:
        kw = {
            "uid": uid,
            "key": temp_key[uid],
            "pswd": pswd,
            "new_pswd": new_pswd
        }
        reply = requests.post(host + 'change_password/', json=kw).json()
        return reply["status"], reply["info"]
    except:
        return False, u"服务器连接错误!"


def search_post(content: str, host=server_host):
    """搜索请求"""
    global img_dir
    try:
        kw = {
            "content": content
        }
        reply = requests.get(host+'search/', json=kw).json()
        for user in reply["User"]:
            img = get_img_post(user["img"])
            if img:
                copy_img(img_dir + user["img"], img)
        for group in reply["Group"]:
            img = get_img_post(group["img"])
            if img:
                copy_img(img_dir + group["img"], img)
        return reply["User"], reply["Group"]
    except:
        return [], []


def friend_application_post(uid, target_uid, host=server_host):
    """好友申请"""
    global temp_key
    try:
        kw = {
            "uid": uid,
            "key": temp_key[uid],
            "target_uid": target_uid
        }
        reply = requests.post(host + 'friend_application/', json=kw).json()
        return reply["status"]
    except:
        return False


def response_friend_application_post(uid, from_uid, response: bool, host=server_host):
    """回应好友申请"""
    global temp_key
    try:
        kw = {
            "uid": uid,
            "key": temp_key[uid],
            "from_uid": from_uid,
            "response": response
        }
        reply = requests.post(host + 'response_friend_application/', json=kw).json()
        return reply["status"]
    except:
        return False


def add_group_post(uid, name, host=server_host):
    """新建群聊"""
    global temp_key
    try:
        kw = {
            "uid": uid,
            "key": temp_key[uid],
            "name": name
        }
        reply = requests.post(host + 'add_group/', json=kw).json()
        return reply["status"]
    except:
        return False


def get_group_info_post(uid, host=server_host):
    """获取群聊信息"""
    try:
        kw = {
            "uid": uid
        }
        reply = requests.get(host + 'get_group_info/', json=kw).json()
        group = reply["group"]
        img = get_img_post(group["img"])
        if img:
            copy_img(img_dir + group["img"], img)
        return group
    except Exception as e:
        print("get_group_info_post:", e)
        return None


def change_group_info_post(uid, info, host=server_host):
    """修改群聊信息"""
    try:
        kw = {
            "uid": uid,
            "info": info
        }
        save_img_post(uid, info["img_path"], "group")
        reply = requests.post(host + 'change_group_info/', json=kw).json()
        return reply["status"]
    except Exception as e:
        print(e)
        return False


def group_application_post(uid, group_uid, host=server_host):
    """群聊申请"""
    global temp_key
    try:
        kw = {
            "uid": uid,
            "key": temp_key[uid],
            "group_uid": group_uid
        }
        reply = requests.post(host + 'group_application/', json=kw).json()
        return reply["status"]
    except:
        return False


def response_group_application_post(uid, from_uid, group_uid, response: bool, host=server_host):
    """回应群聊申请"""
    global temp_key
    try:
        kw = {
            "uid": uid,
            "key": temp_key[uid],
            "group_uid": group_uid,
            "from_uid": from_uid,
            "response": response
        }
        reply = requests.post(host + 'response_group_application/', json=kw).json()
        return reply["status"]
    except:
        return False


def out_group_post(uid, group_uid, host=server_host):
    """退出群聊"""
    global temp_key
    try:
        kw = {
            "uid": uid,
            "key": temp_key[uid],
            "group_uid": group_uid
        }
        reply = requests.post(host + 'out_group/', json=kw).json()
        return reply["status"]
    except:
        return False


def delete_group_post(uid, group_uid, host=server_host):
    """退出群聊"""
    global temp_key
    try:
        kw = {
            "uid": uid,
            "key": temp_key[uid],
            "group_uid": group_uid
        }
        reply = requests.post(host + 'delete_group/', json=kw).json()
        return reply["status"]
    except Exception as e:
        print("delete_group_post:", e)
        return False


def group_invitation_post(uid, group_uid, target_uid, host=server_host):
    """群聊邀请"""
    global temp_key
    try:
        kw = {
            "uid": uid,
            "key": temp_key[uid],
            "target_uid": target_uid,
            "group_uid": group_uid
        }
        reply = requests.post(host + 'group_invitation/', json=kw).json()
        return reply["status"]
    except:
        return False


def response_group_invitation_post(uid, group_uid, response: bool, host=server_host):
    """回应群聊邀请"""
    global temp_key
    try:
        kw = {
            "uid": uid,
            "key": temp_key[uid],
            "group_uid": group_uid,
            "response": response
        }
        reply = requests.post(host + 'response_group_invitation/', json=kw).json()
        return reply["status"]
    except:
        return False


def get_new_friend_post(uid, host=server_host):
    """获取新朋友通知"""
    global temp_key
    try:
        kw = {
            "uid": uid,
            "key": temp_key[uid]
        }
        reply = requests.get(host+'get_new_friend/', json=kw).json()
        return reply["User"], reply["Group"]
    except:
        return [], []


def clear_new_friend_post(uid, mode, host=server_host):
    """清空新朋友消息"""
    global temp_key
    try:
        kw = {
            "uid": uid,
            "key": temp_key[uid],
            "mode": mode
        }
        reply = requests.post(host+'clear_new_friend/', json=kw).json()
        return reply["status"]
    except:
        return False


def delete_friend_post(uid, friend_uid, host=server_host):
    """删除好友"""
    global temp_key
    try:
        kw = {
            "uid": uid,
            "friend_uid": friend_uid,
            "key": temp_key[uid],
        }
        reply = requests.post(host + 'delete_friend/', json=kw).json()
        return reply["status"]
    except:
        return False


def change_remarks_post(uid, friend_uid, name, host=server_host):
    """更改好友备注"""
    global temp_key
    try:
        kw = {
            "uid": uid,
            "friend_uid": friend_uid,
            "name": name,
            "key": temp_key[uid],
        }
        reply = requests.post(host + 'change_remarks/', json=kw).json()
        return reply["status"]
    except:
        return False


def is_friend_post(uid, friend_uid, host=server_host):
    """查询是不是好友"""
    global temp_key
    try:
        kw = {
            "uid": uid,
            "friend_uid": friend_uid,
            "key": temp_key[uid],
        }
        reply = requests.get(host + 'is_friend/', json=kw).json()
        return reply["status"], reply["is_friend"]
    except:
        return None


def get_remarks_post(uid, friend_uid, host=server_host):
    """查询昵称备注"""
    global temp_key
    try:
        kw = {
            "uid": uid,
            "friend_uid": friend_uid,
            "key": temp_key[uid],
        }
        reply = requests.get(host + 'get_remarks/', json=kw).json()
        return reply["status"], reply["remarks"]
    except:
        return None


def get_history_post(uid, target, mode: str, host=server_host):
    """获取聊天历史，mode为friend或group"""
    global temp_key
    global history_dir
    try:
        kw = {
            "uid": uid,
            "target": target,
            "key": temp_key[uid],
            "mode": mode
        }
        reply = requests.get(host+"get_history/", json=kw).json()
        save_dir = history_dir+"u"+uid+"/"
        if not os.path.exists(save_dir):
            os.mkdir(save_dir)
        if not os.path.exists(save_dir+"chat/"):
            os.mkdir(save_dir+"chat/")
        if not os.path.exists(save_dir+"img/"):
            os.mkdir(save_dir+"img/")
        history = reply["history"]  # 字典格式
        for i, dic in enumerate(history["history"]):  # 列表
            bubble_type = dic["bubble_type"]
            if bubble_type == "img":  # 获取一个特殊图片路径
                img_path = os.path.abspath(save_dir+"img/"+md5(uid+target+str(i))+".png").replace("\\", "/")
                if img_path:
                    copy_img(img_path, get_str_base64(dic["text"]))
                    dic["text"] = change_alink(dic["text"], img_path)
            if dic["uid"] == uid:
                dic["isMe"] = True
            else:
                dic["isMe"] = False
        if mode == "friend":
            history_path = save_dir+"chat/u"+target+".json"
        else:
            history_path = save_dir + "chat/g" + target + ".json"
        with open(history_path, "w", encoding="utf-8") as f:
            f.write(json.dumps(history))
        return reply["status"]
    except Exception as m:
        print(m)
        return False


def send_message_post(uid, target, mode: str, msg_dic, host=server_host):
    """发送消息"""
    global temp_key
    try:
        kw = {
            "uid": uid,
            "key": temp_key[uid],
            "target": target,
            "mode": mode,
            "message": msg_dic,
        }
        if not msg_dic["bubble_type"] == "file":
            reply = requests.post(host + "send_message/", json=kw).json()
        else:
            file_path = re.findall(r'<a href=([\s\S]*)><img src=', msg_dic["text"].replace("\\", "/"))[0]
            file_path = file_path.replace('"', "")
            file_path = file_path.replace("?file", "")
            file_path = file_path.replace("file:///", "")
            file_dic = {'file': (os.path.basename(file_path), open(file_path, 'rb'), 'application/json')}
            reply = requests.post(host + "send_message/", json=kw, files=file_dic).json()
        return reply["status"]
    except Exception as e:
        print(e)
        return False


def change_msg_info_num_post(uid, target, mode, num=0, host=server_host):
    """修改消息通知数量"""
    global temp_key
    try:
        kw = {
            "uid": uid,
            "key": temp_key[uid],
            "target": target,
            "mode": mode,
            "num": num
        }
        reply = requests.post(host+"change_msg_info_num/", json=kw).json()
        return reply["status"]
    except:
        return False


if __name__ == "__main__":
    # print(register_post("2444590652", "2444590652", "SouthIO"))
    print(login_post("2444590652", "2444590652"))
    # print(get_user_main_post("2444590652"))
    # print(requests.post(server_host+"test/"))
    print(get_history_post("2444590652", "1927535773", "friend"))
